import moment from 'moment';
import React, { ReactElement, useContext, useEffect, useRef } from 'react';
import { ScrollView, Text, View } from 'react-native';
import Button from '../../../../../../components/Button';
import Mask from '../../../../../../components/Mask';
import { setRecordScroll, setShowRecord } from '../../actions';
import { Store } from '../../reducer';
import Message from '../Message';
import Recording from '../Recording';

import styles from './style';

export default (): ReactElement => {
  const scroll = useRef<ScrollView>(null);

  const { state } = useContext(Store);
  const { messageList, showRecord, dateList } = state;

  useEffect((): void => {
    setRecordScroll(scroll);

    setTimeout((): void => {
      if (scroll && scroll.current) {
        scroll.current.scrollToEnd();
      }
    }, 200);
  }, []);

  return (
    <Mask
      style={[styles.container, showRecord ? {} : styles.hidden]}
      resAlpha={0.5}
      animatedDuration={400}
    >
      <View style={styles.content}>
        <View style={styles.titleContent}>
          <Text style={styles.title}>消息记录</Text>
          <Button
            text="关闭"
            textStyle={styles.closeDesc}
            style={styles.close}
            onPress={(): void => {
              setShowRecord(false);
            }}
            hitSlop={{ left: 20, top: 20, right: 20, bottom: 20 }}
          />
        </View>
        <View style={styles.line} />
        <ScrollView
          ref={scroll}
          horizontal={false}
          contentContainerStyle={styles.listContent}
          style={styles.list}
        >
          {messageList.map(
            (message): ReactElement => {
              const currentTime = dateList.find(
                (date): boolean => date === message.sendTime
              );
              return (
                <View>
                  {currentTime && (
                    <Text style={styles.time}>
                      {moment(currentTime).format('HH:mm')}
                    </Text>
                  )}
                  <Message message={message} />
                </View>
              );
            }
          )}
        </ScrollView>
      </View>
      <Recording />
    </Mask>
  );
};
